<?php

namespace app\index\controller;

use app\admin\model\activtyc\Examiation;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use think\Session;
use think\Cookie;
use think\Db;
class Ques extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $config = [
        'app_id' => 'wx1f8725eef4e232a4',
        'secret' => '422171ef36ac1a93c055d0191cdfb751',
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/index/ques/oauth',
        ]
    ];
    public  $config2 = [
        // 必要配置
        'app_id'             => 'wx1f8725eef4e232a4',
        'mch_id'             => '1502026301',
        'key'                => '7xuEuQHG1nyCihYc0NgU0QAuvQT4sHvt',   // API 密钥
        // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
        'cert_path'          => '../../extend/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
        'key_path'           => '../../extend/cert/apiclient_key.pem',      // XXX: 绝对路径！！！！
        'notify_url'         => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
    ];
    public $app;
    public  $apps = null;

    protected $guess;

    public function _initialize()
    {
        parent::_initialize();
        $this->app = Factory::officialAccount($this->config);

        $this->apps = Factory::payment($this->config2);
        $this->Volumemodel = new \app\admin\model\ques\Volume;
        $this->Logmodel = new \app\admin\model\ques\Log;
        $this->Subjectmodel = new \app\admin\model\ques\VolumeSubject;
        $this->Datamodel = new \app\admin\model\ques\VolumeSubjectData;
        $this->baseSinglemodel = new \app\admin\model\base\Single;
        $this->Singlemodel = new \app\admin\model\activtyc\Single;

        $this->baseSourcemodel = new \app\admin\model\base\Source;
        $this->Guessingmodel = new \app\admin\model\activtyc\Guessing;
        $this->guess = new \app\admin\model\Guess();
         //学校model
        $this->BaseSchoolmodel = new \app\admin\model\base\School;
        $this->QuesSchoolmodel = new \app\admin\model\ques\School;
        $this->Roundmodel = new \app\admin\model\activtyc\Round;
    }

    public function oauth()
    {
        $oauth = $this->app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $_SESSION['wechat_user'] = $user->toArray();
        Session::set('wechat_user',$user->toArray());      
        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
        header('location:'. $targetUrl); // 跳转到 user/profile
        return $response = $this->app->oauth->scopes(['snsapi_userinfo'])
            ->redirect();
    }
    private function getMongoDB($keys){
        if ($keys=='')return false;
        $manager  = new \MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');

        $filter = ['keys'=>$keys];
        $options = [];

        $query = new \MongoDB\Driver\Query($filter, $options);

        $cursor = $manager->executeQuery('db.volume',$query);
        $res='';
        foreach ($cursor as $k=>$document) {

            $res = $document->val;

        }
        if ($res=='')$this->error('请同步数据');
        return json_decode($res,1);


    }
    //方法备份
    private function volume_backs($ids = null){
        $template = 'ques/index';
        $post = [
            'id'=>1,
            'name'=>'123',
            'phone'=>'123',//$formData['phone'],
            'parent_name'=>'123',//$formData['parent_name'],
            // 'type'=>$info['type'],
            'volumename'=>'123',//TableField('Volume','name',$formData['volume_id']),
            'schoolname'=>'123',//TableField('School_B','name',$formData['school_id']),
            'classname'=>'123',//formData['classname'],
            'moban'=>'round'
        ];
        $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
        var_dump($response);
        exit;

        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $oauth = $this->app->oauth;
            // 未登录
            if (!isset($_SESSION['wechat_user'])) {
                $_SESSION['target_url'] = '/index/Ques/volume/ids/'.$ids;
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
                $oauth->redirect()->send();exit;
            }
            $row = $this->Volumemodel->get($ids);
            if (!$row)
                $this->error(__('No Results were found'));
            $now = time();
            if($now < $row->start_time)
                $this->error(__('活动开始时间：'.date("Y-m-d H:i:s",$row->start_time)));
            if($now>= $row->end_time || $row->status == 2)
                return $this->redirect('https://tmall.fc62.com/end_activity.html');
            //学校信息
            if($row['status_school'] == 2){
                //问卷学校
                //$ques_school = $this->QuesSchoolmodel->field('id,school_id')->where(['volume_id'=>$ids])->order('weigh','desc')->cache('ques_school_data')->select();
                //全部学校
                $base_school =$this->BaseSchoolmodel->field('id,name')->order('weigh','asc')->cache('base_school_data')->select();

                //$this->view->assign('ques_school',$ques_school);
                $this->view->assign('base_school',$base_school);
            }

            $info = $this->Subjectmodel->where(['volume_id'=>$ids])->order('weigh','desc')->cache('subject_data')->select();
            // 已经登录过
            $user = $_SESSION['wechat_user'];
            $this->app->jssdk->setUrl('');
            $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay','hideOptionMenu'], $debug = false, $beta = false, $json = true);
            $this->view->assign('jssdk',$jssdk);
            $this->view->assign('row',$row);
            $this->view->assign('info',$info);
            $dati = 0;
            //查询是否答题过
            if($res = $this->Logmodel->get(['volume_id'=>$ids,'openid'=>$user['id']])) $dati =1;
            $edit = null;

            $this->view->assign('dati',$dati);//1为已经答题 0 未答题
            switch ($ids) {
                case 3:
                    //登陆未填写信息
                    if($user){
                        $activity = new \app\admin\model\activtyc\Examiation();
                        $list = $activity->where('openid','=',$user['id'])->find();
                        if($list){
                            switch ($list['type']){
                                case '全国版':{
                                    return $this->redirect('http://uploadfile.fc62.com/caiti/%E7%8C%9C%E9%A2%98%E5%8D%B7-%E5%85%A8%E5%9B%BD-%E5%85%A8.pdf');
                                    break;
                                }
                                case '北京版':{
                                    return $this->redirect('http://uploadfile.fc62.com/caiti/%E7%8C%9C%E9%A2%98%E5%8D%B7-%E5%8C%97%E4%BA%AC-%E5%85%A8.pdf');
                                    break;
                                }
                                case '江苏版':{
                                    return $this->redirect('http://uploadfile.fc62.com/caiti/%E7%8C%9C%E9%A2%98%E5%8D%B7-%E6%B1%9F%E8%8B%8F-%E5%85%A8.pdf');
                                    break;
                                }
                                case '浙江版':{
                                    return $this->redirect('http://uploadfile.fc62.com/caiti/%E7%8C%9C%E9%A2%98%E5%8D%B7-%E6%B5%99%E6%B1%9F-%E5%85%A8.pdf');
                                    break;
                                }
                                case '新高考版':{
                                    return $this->redirect('http://uploadfile.fc62.com/caiti/%E7%8C%9C%E9%A2%98%E5%8D%B7-%E6%96%B0%E9%AB%98%E8%80%83-%E5%85%A8.pdf');
                                    break;
                                }
                            }
                        }else{
                            return $this->view->fetch('ques/examiation');
                        }
                    }else{
                        return $this->view->fetch('ques/examiation');
                    }
                    break;
                case 4:
                    //是否填写过表单  是否支付过
                    if($result = $this->guess->get(['openid'=>$user['id']]))
                    {
                        if($result['status'] == 2)
                        {
                            //支付过
                            return $this->redirect('http://tmall.fc62.com/zm_success.html');
                        }
                        $edit = $result;
                    }
                    break;
                case 5:
                case 6:
                    //是否填写过表单  是否支付过
                    if($result = $this->Roundmodel->get(['openid'=>$user['id'],'volume_id'=>$ids]))
                    {
                        $diqu = $this->Roundmodel->getProvinceOrderList();
                        //成功页面数据数据
                        $return  = [
                            'id'=>32,
                            'name'=>$result['name'],
                            'phone'=>$result['phone'],
                            'province'=>isset($diqu[$result['shen']]) ? $diqu[$result['shen']]: '',
                            'city'=>isset($diqu[$result['shi']]) ? $diqu[$result['shi']] : '',
                            'district'=>isset($diqu[$result['xian']]) ? $diqu[$result['xian']] : '',
                            'detail'=>$result['address'],
                            'school_name'=>TableField('School_B','name',$result['school_id']),
                        ];
                        return $this->redirect(combineURL('https://shoptest.fc62.com/activity/submit_success', $return));
                        $edit = $result;
                    }
                    $area = [
                        'province'=>351,
                        'city'=>362,
                        'area'=>363,
                        'address_text'=>'内蒙古自治区 包头市 东河区',
                    ];
                    $this->view->assign('area',$area);
                    break;
            }
            $this->view->assign('edit',$edit);
            $template = $row['template'];
        }
        return $this->view->fetch($template);
    }
    //判断来源
   public function referer(){
        $referer_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        if(Cookie::has('referer_url')) $referer_url = Cookie::get('referer_url');
        $aSites = ['xiaoeknow.com'];
        $return  = false;
        foreach ($aSites as  $value) {
            if (strpos($referer_url,$value)){
                $return = true;
            }
        }

        if($return && !Cookie::has('referer_url')) Cookie::set('referer_url',$referer_url,36000);
        return [$return,$referer_url];
   }
   public function volume($ids = null){

        $template = 'ques/index';
        //来源
        list($referer_return,$referer_url) = $this->referer();
        $this->view->assign('referer_return',$referer_return);
        $this->view->assign('referer_url',$referer_url);
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $oauth = $this->app->oauth;
            // 未登录
            if (!isset($_SESSION['wechat_user'])) {
               $_SESSION['target_url'] = '/index/Ques/volume/ids/'.$ids;
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
               $oauth->redirect()->send();exit;

            }

            $user = $_SESSION['wechat_user'];

            $keys='volueme_'.$ids;
            $data = $this->getMongoDB($keys);
            $now = time();
           if($data < $data['start_time'])
               $this->error(__('活动开始时间：'.date("Y-m-d H:i:s",$data['start_time'])));
           if($now>= $data['end_time'] || $data['status'] == 2)
               return $this->redirect('https://tmall.fc62.com/end_activity.html');

           $ttlTime=$data['end_time']-time();
           $redis = getRedis();
           $check_key = "check_".$ids.'_'.$user['id'];

            $this->view->assign('row',$data);

           if (!$redis->get($check_key)){
               $this->view->assign('ttl',$ttlTime);
               return $this->view->fetch('ques/check_phone');
           }

            //学校信息
            if($data['status_school'] == 2){
                //问卷学校
                //$ques_school = $this->QuesSchoolmodel->field('id,school_id')->where(['volume_id'=>$ids])->order('weigh','desc')->cache('ques_school_data')->select();
                //全部学校
                if ($ids==34){
                    $base_school =$this->BaseSchoolmodel->field('id,name')->where(array('type'=>3))->order('weigh','asc')->cache('base_school_data')->select();
                }else{
                    $base_school =$this->BaseSchoolmodel->field('id,name')->order('weigh','asc')->cache('base_school_data')->select();

                }
                //$this->view->assign('ques_school',$ques_school);
                $this->view->assign('base_school',$base_school);

            }
          
            $info = $data['subject'];
            // 已经登录过
            $this->app->jssdk->setUrl('');
            $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay','hideOptionMenu'], $debug = false, $beta = false, $json = true);
            $this->view->assign('jssdk',$jssdk);
            $this->view->assign('info',$info);

            $dati = 0;
            $redKeys='dt_'.$ids.'_'.$user['id'];//当前用户存放redkeys
            if ( $redis->get($redKeys)){
                $mobile = $redis->get($check_key);
                $keyss='xt_'.$ids.'_'.$mobile;
                list($cname,$name)=explode('|',$redis->get($keyss));
                $this->view->assign('cname',$cname);
                $this->view->assign('name',$name);

                $this->view->assign('mobile',$mobile);

                $dati=1;
            }

            $formKey='form_'.$ids.'_'.$user['id'];
            if ($redis->get($formKey)){
                switch ($ids) {
                    case 6:
                        $redirect_url = 'https://shoptest.fc62.com/activity/submit_success/32?source=sc';
                        break;
                    case 34:
                        $redirect_url = 'https://shoptest.fc62.com/user/primaty_success';
                        break;
                    default:
                        $redirect_url = 'https://shoptest.fc62.com/';
                        break;
                }
                return $this->redirect($redirect_url);
            }
            //查询是否答题过
           // if($res = $this->Logmodel->get(['volume_id'=>$ids,'openid'=>$user['id']])) $dati =1;

            $edit = null;
             $area = [
                    'province'=>351,
                    'city'=>352,
                    'area'=>353,
                    'address_text'=>'内蒙古自治区 呼和浩特市 新城区',
                ];
                $this->view->assign('area',$area);  
            $this->view->assign('dati',$dati);//1为已经答题 0 未答题

            $this->view->assign('edit',$edit);
            $template = $data['template'];

        }

        return $this->view->fetch($template);
   }
    public function volumetest($ids = null){
        $post =[];
        $row = $this->Volumemodel->get($ids);
        if (!$row)
             $this->error(__('No Results were found'));
        $now = time();
       if($now < $row->start_time)
           $this->error(__('活动开始时间：'.date("Y-m-d H:i:s",$row->start_time)));
       if($now>= $row->end_time)
           $this->error(__('活动已经结束'));
        $info = $this->Subjectmodel->where(['volume_id'=>$ids])->order('weigh','desc')->select();
       // print_r($info[1]->Datas[1]['answer']);die;
        $this->view->assign('row',$row);
        $this->view->assign('info',$info);
        return $this->view->fetch('ques/volume');
    }
    public function checks()
    {
        if ($this->request->isPost() && isset($_SESSION['wechat_user'])) {
            $weUid=$_SESSION['wechat_user']['id'];
            $mobile = trim($_POST['mobile']);
            $name=trim($_POST['signname']);
            $ids=intval($_POST['ids']);
            $ttl=intval($_POST['ttl']);

            $redis = getRedis();
            $keys='xt_'.$ids.'_'.$mobile;

            $info = $redis->get($keys);
            if (!$info)$this->error('您输入的信息不正确');
            list($names,)=explode('|',$info);
            if ($names!=$name)$this->error('您输入的信息不正确');
            $checkKeys='check_'.$ids.'_'.$weUid;
            $str=$mobile;
            $redis->set($checkKeys,$str);
            $redis->expire($checkKeys,$ttl);
            $this->success('操作成功');

        }
    }
    public function volumepost($ids = null){
        if (!$_SESSION['wechat_user'])$this->error('请刷新浏览器');
        $weUid=$_SESSION['wechat_user']['id'];
        $keys='volueme_'.$ids;
        $row = $this->getMongoDB($keys);
        $redKeys='dt_'.$ids.'_'.$weUid;//当前用户存放redkeys
        $redis = getRedis();
        if($redis->get($redKeys))$this->error('当前答疑已经提交过');

        if (!$row)
            $this->error(__('No Results were found'));
        $now = time();
        if($now>= $row['end_time'] || $row['status'] == 2)$this->error("活动已经结束，或者已禁止");
        $info=$row['subject'];
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $correct = 0;
            $all = count($info);

            $countAns=0;//题目对错统计
            $returnData=array();
            foreach ($info as $key => $value) {
                if($value['type'] == 1 && isset($params['wenjuan'.$key])){
                    $wenjuan = explode('-', $params['wenjuan'.$key]);
                    //64-AB选项

                    $isBool = $this->filterRadio($wenjuan[1],$value['timu']);
                    $returnData[]=array('status'=>$isBool ? 2 : 1,'sid'=>$wenjuan[0],'ans'=>$wenjuan[1]);
                }elseif($value['type'] == 2 && isset($params['wenjuan'.$key])){
                    $wenjuanarr = explode('||', $params['wenjuan'.$key]);
                    $wjArr=array();//多选答案组装
                    foreach ($wenjuanarr as $vw){
                        list($ds,$tx,,)=explode('-',$vw);
                        $wjArr[]=$tx;

                    }
                    $isBool = $this->filterBox($wjArr,$value['timu']);
                    $newArr=array('status'=>$isBool ? 2 : 1,'sid'=>$ds,'ans'=>implode(',',$wjArr));
                    $returnData[]=$newArr;

                }
                if ($isBool)$countAns++;
            }


            $a=$redis->set($redKeys,json_encode($returnData));

            $ttl = $row['end_time']-time();

            $redis->expire($redKeys,$ttl);



            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }

    }

    //检查当前题目是否做正确
    private function filterRadio($ques,$data){
        if (!$ques)return false;
        $bool=false;
        foreach ($data as $k=>$v){
            if ($ques==$v['name'] && $v['status']==2){
                $bool=true;
                break;
            }
        }
        return $bool;
    }
    //检查当前题目是否做正确
    private function filterBox($ques,$data){
        if (!$ques)return false;
        $bool=false;
        $assoc=array();
        foreach ($data as $k=>$v){
            if ($v['status']==2){
                $assoc[]=$v['name'];
            }

        }
        //计算两个数组键值
        $inter = array_intersect($ques,$assoc);

        if (count($inter)==count($assoc) && count($assoc)==count($ques))$bool=true;
        return $bool;
    }
    public function volumepost_back($ids = null){
        $keys =
        $row = $this->Volumemodel->get($ids);


         if (!$row)
            $this->error(__('No Results were found'));
          $info = $this->Subjectmodel->where(['volume_id'=>$ids])->order('weigh','desc')->select();   
          if ($this->request->isPost()) {
            $params = $this->request->post(); 
            $correct = 0;
            $all = count($info);
            Db::startTrans();
            foreach ($info as $key => $value) {
                if($value['type'] == 1 && isset($params['wenjuan'.$key])){
                    $wenjuan = explode('-', $params['wenjuan'.$key]);
                       $info_one = $this->Subjectmodel->alias('a')
                        ->field('a.id,a.name as tmname,a.weigh,a.type,a.publish,a.z_publish,b.*')
                        ->where('a.id',$wenjuan[0])
                        ->where('b.name',$wenjuan[1])
                        ->where('b.answer',$wenjuan[2])
                        ->join('hdyj_ques_volume_subject_data b','a.id = b.subject_id')
                        ->find();
                    if($info_one){
                        $this->addlog($info_one,$ids);
                        $result = $this->Datamodel->where(["subject_id"=>$wenjuan[0],"name" => $wenjuan[1], "answer" => $wenjuan[2]])->setInc("num");
                        if(!$result) {
                             Db::rollback();
                            $this->error("操作失败");
                        }
                        if($info_one->status == 2){
                             $correct++;
                        }
                    }
                }elseif($value['type'] == 2 && isset($params['wenjuan'.$key])){
                     $wenjuanarr = explode('||', $params['wenjuan'.$key]);
                        $checkcount = $this->Datamodel
                                ->where('subject_id',$value['id'])
                                ->where('status',2)
                                ->count();
                      $checkbox = 0;
                      foreach ($wenjuanarr as $k => $v) {
                            $wenjuan = explode('-', $v);
                               $info_one = $this->Subjectmodel->alias('a')
                                ->field('a.id,a.name as tmname,a.weigh,a.type,a.publish,a.z_publish,b.*')
                                ->where('a.id',$wenjuan[0])
                                ->where('b.name',$wenjuan[1])
                                ->where('b.answer',$wenjuan[2])
                                ->join('hdyj_ques_volume_subject_data b','a.id = b.subject_id')
                                ->find();
                             if($info_one){
                                $this->addlog($info_one,$ids);
                                $result = $this->Datamodel->where(["subject_id"=>$wenjuan[0],"name" => $wenjuan[1], "answer" => $wenjuan[2]])->setInc("num");

                                if($info_one->status == 2){
                                     $checkbox++;
                                }
                            }
                      }
                      if($checkcount == $checkbox){
                         $correct++;
                      }
                }
            }
            Db::commit();
            if($ids==3){
                $percentage = $correct/$all*100;
                 if($percentage >= $row->ok_rate){
                     $this->success("操作成功");
                 }else{
                     $this->error("您未认真听讲或未认真答题，请重新答题");
                 }
            }

             $this->success("操作成功");
          }else{
             $this->error("操作失败");
          }
    }

    public function chinese(){
        $user = Session::get('wechat_user');
        $row = $this->request->request();
        $activity = new \app\admin\model\activtyc\Chinese;
        unset($row['s']);
        if($activity->where('phone','=',$row['phone'])->find()){
            $this->error('已经领取,不可重复领取。');
        }
        $row['openid'] = $user['id'];
        $row['url'] = $user['avatar'];
        $result = $activity->allowField(true)->save($row);
        if ($result !== false) {
             $info = $activity->get($activity->getLastInsID());
             $diqu = $activity->getProvinceOrderList();
             $shen_text = isset($diqu[$info->shen]) ? $diqu[$info->shen] : '';
             $shi_text = isset($diqu[$info->shi]) ? $diqu[$info->shi] : '';
             $xian_text = isset($diqu[$info->xian]) ? $diqu[$info->xian] : '';
             $post = [
                'id'=>$info->id,
                'name'=>$info->name,
                'phone'=>$info->phone,
                'address'=>$shen_text.$shi_text.$xian_text,
                'text'=>$info->address,
                'moban'=>'chinese',
            ];
            $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }
    public function  aaaa(){
        $redis = getRedis();
        for ($i=0;$i<10000;$i++){
            echo '3'.PHP_EOL;
            $redis->lPush('form_6','6||ovS7ms__lvCxtozYTV2T9XF17728');//根据活动来
        }


    }
     public function schoolNotify(){

         $response = $this->apps->handlePaidNotify(function($message, $fail){

         });
         $response->send(); // return $response;

     }
     public function school(){
        $user = Session::get('wechat_user');

        $row = $this->request->request();

        $Round = new \app\admin\model\activtyc\Round;
        $redis=getRedis();
         $formKey='form_'.$row['volume_id'].'_'.$user['id'];
         if ($redis->get($formKey)){
             $this->error("当前答疑已经提交过");
         }
         $ttl = $redis->ttl('dt_'.$row['volume_id'].'_'.$user['id']);

         unset($row['s']);
         if($row['school'] == '-1'){
             $school_id = $row['totalschool'];
             $this_school = 0;
             $type_school = 2;
         }else{
             $row['school'] = explode('-', $row['school']);
             $school_id = $row['school'][1];
             $this_school = $row['school'][0];
             $type_school = 1;
         }
         $row['openid'] = $user['id'];
         $row['url'] = $user['avatar'];
         $row['shen']='';
         $row['shi']='';
         $row['xian']='';
         $row['pays']=1;
         $row['address']='';
         $info = [
             'volume_id'=>$row['volume_id'],
             'shen'=>$row['shen'],
             'shi'=>$row['shi'],
             'xian'=>$row['xian'],
             'name'=>$row['name'],
             'pays'=>$row['pays'],
             'parent_name'=>$row['parent_name'],
             'phone'=>$row['phone'],
             // 'type'=>$row['type'],
             'address'=>$row['address'],
             'type_school'=>$type_school,
             'school_id'=>$school_id,
             'this_school'=>$this_school,
             'classname'=>$row['classname'],
             'openid'=>$user['id'],
             'url'=>$user['avatar'],
             'tableName'=>$row['volume_id']==34 ? 'activity_xiaoxue' : 'activity_round'
         ];


         if ($row['volume_id']==34)$info['grade']=$row['grade'];
        //if ($row['pays']==2 || ($row['volume_id']==6 && $row['pays']==3)){
         if ($row['pays']==2 ){
            $ttl = $redis->ttl('dt_'.$row['volume_id'].'_'.$user['id']);
            $out_trade_no = 'hdyj'.date('ymdhis').random(6,'00123456789');
            $result = $this->apps->order->unify([
                'body' => '《考前突破卷》领取纸质版',
                'out_trade_no' => $out_trade_no,
                'total_fee' => 900,
                'notify_url' => 'http://oa.fc62.com/api/Activity/schoolNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $user['id'],
            ]);
            $jssdk = $this->apps->jssdk;
            $json = $jssdk->bridgeConfig($result['prepay_id']);
            $dataJson = json_decode($json,1);
            $dataJson['code']=2;
            $redis->set('temp_'.$out_trade_no,json_encode($info));
            $redis->expire('temp_'.$out_trade_no,$ttl+7200);
            //调用支付
            exit(json_encode($dataJson));
        }else{
            $redKeys='form_'.$row['volume_id'].'_'.$user['id'];

            $redis->set($redKeys,json_encode($info));
            $redis->expire($redKeys,$ttl);
            $redis->lPush('form_data',$row['volume_id'].'||'.$user['id']);//根据活动来

          /*  $diqu = $Round->getProvinceOrderList();
            $shen_text = isset($diqu[$info['shen']]) ? $diqu[$info['shen']] : '';
            $shi_text = isset($diqu[$info['shi']]) ? $diqu[$info['shi']] : '';
            $xian_text = isset($diqu[$info['xian']]) ? $diqu[$info['xian']] : '';*/
            $return  = [
                'id'=>32,
                'name'=>$row['name'],
                'phone'=>$row['phone'],

                'school_name'=>TableField('School_B','name',$info['school_id'])
            ];
             switch ($row['volume_id']) {
                    case 6:
                        $redirect_url = combineURL('https://shoptest.fc62.com/activity/submit_success', $return).'?source=sc';
                        break;
                    case 34:
                        $redirect_url = 'https://shoptest.fc62.com/user/primaty_success';
                        break;
                    default:
                        $redirect_url = 'https://shoptest.fc62.com/';
                        break;
                }
            $this->success('添加成功','',$redirect_url);
        }
    

        /* $Round = new \app\admin\model\activtyc\Round;
         $diqu = $Round->getProvinceOrderList();
         $shen_text = isset($diqu[$info['shen']]) ? $diqu[$info['shen']] : '';
         $shi_text = isset($diqu[$info['shi']]) ? $diqu[$info['shi']] : '';
         $xian_text = isset($diqu[$info['xian']]) ? $diqu[$info['xian']] : '';
         $post = [
             'id'=>$redKeys,
             'name'=>$info['name'],
             'phone'=>$info['phone'],
             'parent_name'=>$info['parent_name'],
             'address'=>$shen_text.$shi_text.$xian_text,
             'text'=>$info['address'],
             // 'type'=>$info['type'],
             'volumename'=>TableField('Volume','name',$info['volume_id']),
             'schoolname'=>TableField('School_B','name',$info['school_id']),
             'classname'=>$info['classname'],
             'moban'=>'round',
         ];*/

         //成功页面数据数据
        /* $return  = [
             'id'=>32,
             'name'=>$post['name'],
             'phone'=>$post['phone'],
             'province'=>$shen_text,
             'city'=>$shi_text,
             'district'=>$xian_text,
             'detail'=>$info['address'],
             'school_name'=>$post['schoolname'],
         ];*/
         //队列之后再发$response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);

         //$this->success('添加成功','',combineURL('https://shoptest.fc62.com/activity/submit_success', $return));



//        if ($result !== false) {
//             $id = $Round->getLastInsID();
//             $diqu = $Round->getProvinceOrderList();
//             $shen_text = isset($diqu[$info['shen']]) ? $diqu[$info['shen']] : '';
//             $shi_text = isset($diqu[$info['shi']]) ? $diqu[$info['shi']] : '';
//             $xian_text = isset($diqu[$info['xian']]) ? $diqu[$info['xian']] : '';
//             $post = [
//                'id'=>$id,
//                'name'=>$info['name'],
//                'phone'=>$info['phone'],
//                'parent_name'=>$info['parent_name'],
//                'address'=>$shen_text.$shi_text.$xian_text,
//                'text'=>$info['address'],
//                // 'type'=>$info['type'],
//                'volumename'=>TableField('Volume','name',$info['volume_id']),
//                'schoolname'=>TableField('School_B','name',$info['school_id']),
//                'classname'=>$info['classname'],
//                'moban'=>'round',
//            ];
//
//            //成功页面数据数据
//            $return  = [
//                'id'=>32,
//                'name'=>$post['name'],
//                'phone'=>$post['phone'],
//                'province'=>$shen_text,
//                'city'=>$shi_text,
//                'district'=>$xian_text,
//                'detail'=>$info['address'],
//                'school_name'=>$post['schoolname'],
//            ];
//            $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
//            $this->success('添加成功','',combineURL('https://shoptest.fc62.com/activity/submit_success', $return));
//        } else {
//            $this->error('添加失败');
//        }
    }

    public function examiation(){
        $user = Session::get('wechat_user');
        $row = $this->request->request();
        $activity = new \app\admin\model\activtyc\Examiation();
        unset($row['s']);
        if($activity->where('phone','=',$row['phone'])->find()){
            $this->error('已经领取,不可重复领取。');
        }
        $row['openid'] = $user['id'];
        $row['url'] = $user['avatar'];
        $result = $activity->allowField(true)->save($row);
        if ($result !== false) {
            $info = $activity->get($activity->getLastInsID());
            $diqu = $activity->getProvinceOrderList();
            $shen_text = isset($diqu[$info->shen]) ? $diqu[$info->shen] : '';
            $shi_text = isset($diqu[$info->shi]) ? $diqu[$info->shi] : '';
            $xian_text = isset($diqu[$info->xian]) ? $diqu[$info->xian] : '';
            $post = [
                'id'=>$info->id,
                'name'=>$info->name,
                'phone'=>$info->phone,
                'address'=>$shen_text.$shi_text.$xian_text,
                'type'=>$info->type,
                'moban'=>'examiation',
            ];
            $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }
    public function teacher(){
        if ($this->request->isPost()) {
            $row = $this->request->request();
            $teacher = new \app\admin\model\activity\Teacher();
            unset($row['s']);

            if($teacher->where('tel','=',$row['tel'])->find()){
                $this->error('已经领取,不可重复领取。');
            }
            if($_FILES){
                $row['thumb_img']='';
                $img = ROOT_PATH."public/uploads/teacher/".date("YmdHis",time()).md5(rand(0,100)*5).'.jpg';

                if(move_uploaded_file($_FILES['Filedata']['tmp_name'],$img)){
                    $row['thumb_img']=str_replace("oa.fc62.com/",'http://oa.fc62.com/',str_replace(array("/www/wwwroot/",'public/'),'',$img));
                }

            }
            $result = $teacher->allowField(true)->save($row);

            if ($result !== false) {
                $info = $teacher->get($teacher->getLastInsID());
                if($info->subject==2){
                    if($info->banben==1){
                        $info->banben = "北师版";
                    }elseif ($info->banben==2){
                        $info->banben = "苏教版";
                    }elseif ($info->banben==3){
                        $info->banben = "人教版";
                    }elseif ($info->banben==4){
                        $info->banben = "沪教版";
                    }
                }else{
                    $info->banben = "";
                }
                $info->subject = $info->subject ==1 ? "语文" :'数学';

                $info->createtime = date("Y-m-d H:i:s",$info->createtime);
                $post = [
                    'id'=>$info->id,
                    'name'=>$info->name,
                    'phone'=>$info->tel,
                    'school'=>$info->school,
                    'subject'=>$info->subject,
                    'banben'=>$info->banben,
                    'createtime'=>$info->createtime,
                    'moban'=>'teacher',
                ];
                $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
                libxml_disable_entity_loader(false);
                $client = new \SoapClient('http://api.sms.hsyid.com:8088/XDTWebService.asmx?wsdl');
                $aryPara = array(
                    'user'=>'hdyjsys',
                    'pwd'=>'hdyjsys323',
                    'mobiles'=>$info->tel,
                    'contents'=>'【宏达一甲】老师您好！您已成功免费申领《小学生绘本课堂》，请保持手机畅通，我们将尽快与您取得联系，如有任何问题，请咨询全国统一客服热线：4006786665。'
                );
                $response = $client->SendMessage($aryPara);
                echo json_encode(array("status"=>0,"msg"=>"添加成功"));
            } else {
                echo json_encode(array("status"=>1,"msg"=>"添加失败"));
            }
        }else{
            return $this->view->fetch('ques/teacherForm');
        }

    }

    public function teacher_success(){
        return $this->view->fetch('ques/success');
    }
    public function addlog($wenjuan = null,$volume_id){
        $user = Session::get('wechat_user');
            $this->Logmodel->insert(array(
                "subject_id"=>$wenjuan->id,
                "volume_id"=>$volume_id,
                'name'=>$wenjuan->name,
                'answer'=>$wenjuan->answer,
                'status'=>$wenjuan->status,
                'openid'=>$user['id'],
                'createtime'=>time(),
            ));
        return true;
    }
    public function single($ids = null)
    {
        if(!$ids)  $this->error("参数错误");
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $oauth = $this->app->oauth;
            // 未登录
            if (empty($_SESSION['wechat_user'])) {

                $_SESSION['target_url'] = '/index/ques/single/ids/'.$ids;
//            return $oauth->redirect();
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
                $oauth->redirect()->send();
            }
            $row = $this->baseSinglemodel->get($ids);
            if (!$row)
                $this->error(__('No Results were found'));
            if(!$row['switch']) $this->error("活动已关闭");
            // 已经登录过
            $user = $_SESSION['wechat_user'];
            $this->app->jssdk->setUrl('');
            $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay'], $debug = false, $beta = false, $json = true);
            $this->view->assign('jssdk',$jssdk);
            $this->view->assign('row',$row);
            return $this->view->fetch();
        }
        return $this->view->fetch('ques/indexsingle');
    }
    public function single_success($ids = null){
        if(!$ids)  $this->error("参数错误");
         $row = $this->baseSinglemodel->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        if(!$row['switch']) $this->error("活动已关闭");
        $user = $_SESSION['wechat_user'];
        $info = $this->Singlemodel->where('openid','=',$user['id'])->where('pay','=',1)->where('type','=',$row['id'])->find();
        if(!$info) $this->error("请先支付",'/index/ques/single/ids/'.$ids);
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }  
    public function sale($ids = null){
    //print_r(config('site.guessing_price'));die;
        if(!$ids)  $this->error("参数错误");
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $oauth = $this->app->oauth;
            // 未登录
            if (empty($_SESSION['wechat_user'])) {

                $_SESSION['target_url'] = '/index/ques/sale/ids/'.$ids;
//            return $oauth->redirect();
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
                $oauth->redirect()->send();
            }
              $row = $this->baseSourcemodel->get($ids);
            if (!$row)
                $this->error(__('No Results were found'));
          
            // 已经登录过
            $user = $_SESSION['wechat_user'];
            $this->app->jssdk->setUrl('');
            $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay'], $debug = false, $beta = false, $json = true);
            $this->view->assign('jssdk',$jssdk);
            $this->view->assign('row',$row);
            return $this->view->fetch();
        }
        return $this->view->fetch('ques/indexsale');
    }

    public function recruit()
    {
        return $this->view->fetch();
    }





}
